package tom.vertx.core.demo07;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import lombok.extern.slf4j.Slf4j;

import java.time.Instant;

/**
 * shareData可以在同一个应用、同一个vertx实例多个verticle之间，集群vertx实例间共享数据(集群依赖cluster manager)
 *    localXXX: 同应用多verticle实例间共享
 *    asyncXXX: 集群内多vertx实例节点间数据共享
 * @implNote
 *    本地LocalMap数据共享
 * @author ZHUFEIFEI
 */
@Slf4j
public class ShareData01LocalMapDemo {

  public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    vertx.deployVerticle(new V1());
    vertx.deployVerticle(new V2());
  }

  static class V1 extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {

      vertx.setPeriodic(3000L, id -> {
        //localMap 共享数据 同步获取
        vertx.sharedData().getLocalMap("myLocalMap").put("hello", this.getClass().getName() + Instant.now());
        log.info("{} get shareData => {}", this.getClass().getName(), vertx.sharedData().getLocalMap("myLocalMap1").get("world"));
      });

      startPromise.complete();
    }
  }

  static class V2 extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {

      vertx.setPeriodic(3000L, id -> {
        vertx.sharedData().getLocalMap("myLocalMap1").put("world", this.getClass().getName() + Instant.now());
        log.info("{} get shareData => {}", this.getClass().getName(), vertx.sharedData().getLocalMap("myLocalMap").get("hello"));
      });

      startPromise.complete();
    }
  }

}
